

package com.hazelcast.client.impl.protocol.task;

import com.hazelcast.client.impl.operations.OperationFactoryWrapper;
import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.instance.impl.Node;
import com.hazelcast.internal.namespace.NamespaceUtil;
import com.hazelcast.internal.nio.Connection;
import com.hazelcast.internal.util.collection.PartitionIdSet;
import com.hazelcast.map.impl.MapService;
import com.hazelcast.map.impl.MapServiceContext;
import com.hazelcast.map.impl.operation.MapOperationProvider;
import com.hazelcast.spi.impl.operationservice.OperationFactory;
import com.hazelcast.spi.impl.operationservice.OperationService;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

public abstract class AbstractMultiPartitionMessageTask<P> extends AbstractAsyncMessageTask<P, Map<Integer, Object>> {

    protected AbstractMultiPartitionMessageTask(ClientMessage clientMessage, Node node, Connection connection) {
        super(clientMessage, node, connection);
    }

    @Override
    protected void processMessage() {
        // Inheritors of AbstractMultiPartitionMessageTask are always Namespace-aware
        NamespaceUtil.runWithNamespace(nodeEngine, getUserCodeNamespace(), super::processMessage);
    }

    @Override
    protected CompletableFuture<Map<Integer, Object>> processInternal() {
        OperationFactory operationFactory = new OperationFactoryWrapper(createOperationFactory(), endpoint.getUuid());
        OperationService operationService = nodeEngine.getOperationService();
        return operationService.invokeOnPartitionsAsync(getServiceName(), operationFactory, getPartitions());
    }

    public abstract PartitionIdSet getPartitions();

    protected final MapOperationProvider getMapOperationProvider(String mapName) {
        MapService mapService = getService(MapService.SERVICE_NAME);
        MapServiceContext mapServiceContext = mapService.getMapServiceContext();
        return mapServiceContext.getMapOperationProvider(mapName);
    }

    protected abstract String getUserCodeNamespace();

    protected abstract OperationFactory createOperationFactory();

    protected abstract Object reduce(Map<Integer, Object> map);

    @Override
    protected Object processResponseBeforeSending(Map<Integer, Object> response) {
        return reduce(response);
    }
}
